package me.cloud.common.transmitter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import me.boot.common.constant.Const;
import me.boot.common.context.ContextUtil;
import me.boot.common.data.model.UserInfo;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * @Description:
 * @author: Sylar
 * @date: 2021年09月28日 4:30 下午
 */
@Slf4j
public class TransmitUserInfoFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        this.initUserInfo((HttpServletRequest) request);
        chain.doFilter(request, response);
    }


    private void initUserInfo(HttpServletRequest request) {
        String userJson = request.getHeader(Const.KEY_USERINFO_IN_HTTP_HEADER);
        if (StrUtil.isNotBlank(userJson)) {
            try {
                userJson = URLDecoder.decode(userJson, "UTF-8");
                UserInfo userInfo = JSONUtil.toBean(userJson, UserInfo.class);
                //将UserInfo放入上下文中
                ContextUtil.setUser(userInfo);
            } catch (UnsupportedEncodingException e) {
                log.error("init userInfo error", e);
            }
        }
    }
}
